<template>
  <div class="user-list">
    <div class="header">
      <h2>用户列表</h2>
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        添加用户
      </el-button>
    </div>

    <el-form :model="searchForm" inline class="search-form">
      <el-form-item label="用户名">
        <el-input v-model="searchForm.username" placeholder="请输入用户名" clearable />
      </el-form-item>
      <el-form-item label="手机号">
        <el-input v-model="searchForm.mobile" placeholder="请输入手机号" clearable />
      </el-form-item>
      <el-form-item label="用户类型">
        <el-select 
          v-model="searchForm.userType" 
          placeholder="请选择用户类型" 
          clearable
          filterable
        >
          <el-option label="系统用户" :value="'系统用户'" />
          <el-option label="接口用户" :value="'接口用户'" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态">
        <el-select 
          v-model="searchForm.status" 
          placeholder="请选择状态" 
          clearable
          filterable
        >
          <el-option label="启用" :value="1" />
          <el-option label="禁用" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="userList" border style="width: 100%">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="username" label="用户名" />
      <el-table-column prop="nickname" label="昵称" />
      <el-table-column prop="mobile" label="手机号" />
      <el-table-column prop="userType" label="用户类型" />
      <el-table-column prop="status" label="状态" />
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <el-button-group>
            <el-button type="primary" size="small" @click="handleEdit(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加用户' : '编辑用户'"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" />
        </el-form-item>
        <el-form-item label="密码" v-show="dialogType === 'add'">
          <el-input v-model="form.password" />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="form.nickname" />
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="form.mobile" />
        </el-form-item>
        <el-form-item label="用户类型" prop="userType">
          <el-select v-model="form.userType" style="width: 100%">
            <el-option label="系统用户" :value="'系统用户'" />
            <el-option label="接口用户" :value="'接口用户'" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="'启用'">启用</el-radio>
            <el-radio :label="'禁用'">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="form.gender" style="width: 100%">
            <el-option label="男" :value="'男'" />
            <el-option label="女" :value="'女'" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { Plus, Edit, Delete } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { addOrUpdateUser, deleteUser, getUserPage } from '../../api/user'
import { defaultUser, type User } from '../../types/user'

const userList = ref<User[]>([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const formRef = ref<FormInstance>()

const form = reactive({ ...defaultUser })

const rules = reactive<FormRules>({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  mobile: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ]
})

const searchForm = reactive({ ...defaultUser })

const handleSearch = () => {
  currentPage.value = 1
  fetchUserPage()
}

const resetSearch = () => {
  Object.assign(searchForm, { ...defaultUser })
  handleSearch()
}

const fetchUserPage = async () => {
  const pageData = await getUserPage({
    page: currentPage.value,
    size: pageSize.value,
    ...searchForm
  })
  userList.value = pageData.records
  total.value = pageData.count
}

const handleSizeChange = (val: number) => {
  pageSize.value = val
  fetchUserPage()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  fetchUserPage()
}

const handleAdd = () => {
  dialogType.value = 'add'
  Object.assign(form, { ...defaultUser })
  dialogVisible.value = true
}

const handleEdit = (row: User) => {
  dialogType.value = 'edit'
  Object.assign(form, row)
  dialogVisible.value = true
}

const handleDelete = (row: User) => {
  ElMessageBox.confirm('确定要删除该用户吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const result = await deleteUser(row.id)
    if (result) {
      fetchUserPage()
    }
  }).catch(() => {
    ElMessage.info('已取消删除操作')
  })
}

const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate().then(async (valid) => {
    if (valid) {
      const result = await addOrUpdateUser(form, dialogType.value === 'add')
      if (result) {
        dialogVisible.value = false
        fetchUserPage()
      }
    }
  }).catch(() => {
    ElMessage.error('表单验证失败')
  })
}

onMounted(() => {
  fetchUserPage()
})
</script>

<style scoped>
.user-list {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
  color: var(--el-text-color-primary);
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.search-form {
  margin-bottom: 20px;
  padding: 20px;
  background-color: var(--el-bg-color-page);
  border-radius: 4px;
}

:deep(.el-input__inner:focus) {
  box-shadow: none !important;
  border-color: var(--el-border-color) !important;
}

:deep(.el-select .el-input__inner:focus) {
  box-shadow: none !important;
  border-color: var(--el-border-color) !important;
}

:deep(.el-select .el-input__inner) {
  color: var(--el-text-color-regular);
}

:deep(.el-select .el-input__inner::placeholder) {
  color: var(--el-text-color-placeholder);
}

:deep(.el-input),
:deep(.el-select) {
  width: 200px;
}
</style>